package com.lu.controller;

import com.lu.mapper.NewsCommentMapper;
import com.lu.mapper.NewsMapper;
import com.lu.pojo.News;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "news")
@RestController
@CrossOrigin
public class NewsController {

    @Resource
    private NewsCommentMapper newsCommentMapper;

    @Resource
    private NewsMapper newsMapper;

    @ApiOperation("获取全部新闻")
    @GetMapping("/getNews")
    public List<com.lu.pojo.News> getNews(){
        return newsMapper.selectList(null);
    }


    @ApiOperation("添加新闻")
    @PostMapping("/InsertNews/{category}/{title}/{author}/{readTimes}/{content}")
    public int InsertNews(@PathVariable("category")String category,@PathVariable("title")String title,@PathVariable("author")String author,@PathVariable("readTimes")int readTimes,@PathVariable("content")String content){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        News news = new News();
        news.setCategory(category);
        news.setTitle(title);
        news.setAuthor(author);
        news.setPubTime(dateFormat.format(new Date()));
        news.setContent(content);
        news.setReadTimes(readTimes);
        return newsMapper.insert(news);
    }


    @ApiOperation("删除新闻")
    @PostMapping("/DeleteNews/{id}")
    public int DeleteNews(@PathVariable("id")int id){
        Map<String, Object> map = new HashMap<>();
        map.put("fk_news_id",id);
        newsCommentMapper.deleteByMap(map);
        return newsMapper.deleteById(id);
    }

    @ApiOperation("编辑新闻")
    @PostMapping("/UpdateNews")
    public int UpdateNews(@RequestBody News news){
        return newsMapper.updateById(news);
    }


}
